package cn.vcjf.weapp.api.goods.service.impl;

import cn.vcjf.weapp.api.active.entity.GoodsActiveRecord;
import cn.vcjf.weapp.api.active.entity.GoodsSetmeal;
import cn.vcjf.weapp.api.active.entity.GoodsSetmealDetail;
import cn.vcjf.weapp.api.active.service.GoodsActiveRecordService;
import cn.vcjf.weapp.api.active.service.GoodsSetmealDetailService;
import cn.vcjf.weapp.api.active.service.GoodsSetmealService;
import cn.vcjf.weapp.api.goods.entity.GoodsDiscount;
import cn.vcjf.weapp.api.goods.entity.GoodsGroup;
import cn.vcjf.weapp.api.goods.entity.GoodsOrder;
import cn.vcjf.weapp.api.goods.entity.GoodsOrderItem;
import cn.vcjf.weapp.api.goods.mapper.GoodsOrderItemMapper;
import cn.vcjf.weapp.api.goods.mapper.GoodsOrderMapper;
import cn.vcjf.weapp.api.goods.service.GoodsDiscountService;
import cn.vcjf.weapp.api.goods.service.GoodsGroupService;
import cn.vcjf.weapp.api.goods.service.GoodsOrderService;
import cn.vcjf.weapp.api.payment.QfWxPayController;
import cn.vcjf.weapp.api.setting.entity.OrderOptionConfig;
import cn.vcjf.weapp.api.user.entity.UserDiscount;
import cn.vcjf.weapp.api.user.mapper.UserDiscountMapper;
import cn.vcjf.weapp.common.web.TableResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhengzihang
 * @since 2018-09-25
 */
@Service("goodsOrderService")
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements GoodsOrderService {

	private Logger logger = LogManager.getLogger(GoodsOrderServiceImpl.class);

	@Resource
	private GoodsActiveRecordService goodsActiveRecordService;
	@Resource
	private GoodsGroupService goodsGroupService;
	@Resource
	private GoodsDiscountService goodsDiscountService;
	@Resource
	private UserDiscountMapper userDiscountMapper;
	@Resource
	private GoodsOrderItemMapper goodsOrderItemMapper;
	@Resource
	private GoodsSetmealService goodsSetmealService;
	@Resource
	private GoodsSetmealDetailService goodsSetmealDetailService;
	@Resource
	private OrderOptionConfig orderOptionConfig;

	@Override
	public TableResult addGoodsOrder(GoodsOrder goodsOrder) {
		TableResult result = null;
		Integer orderType = goodsOrder.getOrderType();
		logger.info("添加商品支付订单......生成支付链接.......开始:{}", JSON.toJSON(goodsOrder));
		if (orderType == GoodsOrder.ORDER_TYPE_GEN) {
			result = addGenetateOrder(goodsOrder);
		//砍价订单
		}else if (orderType == GoodsOrder.ORDER_TYPE_CUT) {
			result = addCutPriceOrder(goodsOrder);
		}else if (orderType == GoodsOrder.ORDER_TYPE_TEAM) {

		//套餐订单
		}else if (orderType == GoodsOrder.ORDER_TYPE_COMBOS) {
			result = addSetmealOrder(goodsOrder);
		}
		logger.info("添加商品支付订单......生成支付链接.......返回:{}",JSON.toJSON(result));
		return result;
	}

	/**
	 * 修改用户过期的订单的状态
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public int updateExpireUserOrder(Integer userId) {
		return baseMapper.updateExpireUserOrder(userId, orderOptionConfig.genAutoFailedTime,
				orderOptionConfig.teamAutoFailedTime,
				orderOptionConfig.cutAutoFailedTime,
				orderOptionConfig.autoCompletDate);
	}

	/**
	 * 获取优惠券的价格
	 * @param discountId  优惠券Id
	 * @return
	 */
	public BigDecimal getDiscountPrice(Integer discountId){
		GoodsDiscount goodsDiscount = goodsDiscountService.selectById(discountId);
		return goodsDiscount.getPrice();
	}
	/**
	 *普通订单
	 */
	private TableResult addGenetateOrder(GoodsOrder goodsOrder){
		goodsOrder.preInsert();
		List<GoodsOrderItem> orderItems = goodsOrder.getOrderItems();

		//获取优惠券价格
		BigDecimal discountPrice = getDiscountPrice(goodsOrder.getDiscountId());

		BigDecimal goodsTotalPrice = new BigDecimal(0);
		//计算总价
		for(GoodsOrderItem item :orderItems) {
			Integer goodsGroupId = item.getGoodsId();
			GoodsGroup goodsGroup = goodsGroupService.selectById(goodsGroupId);
			//累加商品总价
			goodsTotalPrice = goodsTotalPrice.add(goodsGroup.getGoodsPrice().multiply(new BigDecimal(item.getGoodsNum())));

			item.setOrderNo(goodsOrder.getOrderNo());
			item.setGoodsId(goodsGroup.getGoodsId());
			item.setGroodsGroupId(goodsGroupId);
			//成交价格
			item.setGoodsPrice(goodsGroup.getGoodsPrice());
			goodsOrderItemMapper.insert(item);
		}

		//商品成交价格  = (商品原单价格 x 数量) - 优惠券价格
		goodsOrder.setTraMoney(goodsTotalPrice);
		goodsOrder.setTraActualMoney(goodsTotalPrice.subtract(discountPrice));
		goodsOrder.setDiscountMoney(discountPrice);

		boolean b = this.insert(goodsOrder);
		//修改优惠券的状态
		UserDiscount userDiscount = new UserDiscount();
		userDiscount.setUserId(goodsOrder.getUserId());
		userDiscount.setDiscountId(goodsOrder.getDiscountId());
		//0,未使用,1,已使用
		userDiscount.setUseStatus(1);
		userDiscountMapper.updateByUserIdAndDiscountId(userDiscount);
		//TODO 构造下单支付链接
		String params = QfWxPayController.getQfWxPayUrl(goodsOrder);
		//TODO 返回下单支付链接
		return TableResult.DateResult(params);
	}
	/**
	 * 砍价订单
	 * @param goodsOrder
	 * @return
	 */
	private TableResult addCutPriceOrder(GoodsOrder goodsOrder) {
		//活动记录详情id
		Integer collageOrderId = goodsOrder.getCollageOrderId();
		GoodsActiveRecord goodsActiveRecord = goodsActiveRecordService.selectById(collageOrderId);

		BigDecimal cutedPrice = goodsActiveRecord.getCutedPrice();

		Integer goodsGroupId = goodsActiveRecord.getGoodsGroupId();
		GoodsGroup goodsGroup = goodsGroupService.selectById(goodsGroupId);
		BigDecimal goodsPrice = goodsGroup.getGoodsPrice();
		//成交价
		goodsOrder.setTraMoney(goodsPrice);
		goodsOrder.setTraActualMoney(goodsPrice.subtract(cutedPrice));
		goodsOrder.setDiscountMoney(null);

		goodsOrder.preInsert();
		boolean b = this.insert(goodsOrder);
		//订单商品
		GoodsOrderItem item = new GoodsOrderItem();
		//成交价格
		item.setTradPrice(goodsOrder.getTraMoney());
		item.setOrderNo(goodsOrder.getOrderNo());
		item.setGoodsId(goodsGroup.getGoodsId());
		item.setGroodsGroupId(goodsGroupId);
		item.setGoodsNum(1);
		item.preInsert();
		goodsOrderItemMapper.insert(item);
		//TODO 构造下单支付链接
		String params = QfWxPayController.getQfWxPayUrl(goodsOrder);
		//TODO 返回下单支付链接
		return TableResult.DateResult(params);
	}
	/**
	 * 套餐订单
	 * @param goodsOrder
	 * @return
	 */
	private TableResult addSetmealOrder(GoodsOrder goodsOrder) {
		//套餐记录详情id
		Integer collageOrderId = goodsOrder.getCollageOrderId();
		GoodsSetmeal goodsSetmeal = goodsSetmealService.selectById(collageOrderId);
		//套餐价
		BigDecimal setMealPrice = goodsSetmeal.getSetMealPrice();
		//优惠券价格
		BigDecimal discountPrice = getDiscountPrice(goodsOrder.getDiscountId());

		//商品成交价格  = (套餐价) - 优惠券价格
		BigDecimal tranPrice = setMealPrice.subtract(discountPrice).setScale(2);
		goodsOrder.setTraMoney(goodsSetmeal.getOriginalPrice());
		goodsOrder.setTraActualMoney(tranPrice);
		goodsOrder.setDiscountMoney(discountPrice);

		goodsOrder.preInsert();
		boolean b = this.insert(goodsOrder);

		//获取套餐详情
		Wrapper<GoodsSetmealDetail> gdWrapper = new EntityWrapper<>();
		gdWrapper.eq("setmealId",collageOrderId);
		List<GoodsSetmealDetail> goodsSetmealDetails = goodsSetmealDetailService.selectList(gdWrapper);
		//订单商品
		for(GoodsSetmealDetail item :goodsSetmealDetails) {
			Integer goodsGroupId = item.getGoodsId();
			GoodsGroup goodsGroup = goodsGroupService.selectById(goodsGroupId);

			GoodsOrderItem orderItem = new GoodsOrderItem();
			orderItem.setGoodsId(goodsGroupId);
			orderItem.setGoodsId(goodsGroup.getGoodsId());

			orderItem.setGoodsNum(item.getGoodsNum());
			orderItem.setOrderNo(goodsOrder.getOrderNo());
			//原价格
			orderItem.setGoodsPrice(goodsGroup.getGoodsPrice());
			//成交价格
//			orderItem.setTradPrice();
			goodsOrderItemMapper.insert(orderItem);
		}
		//TODO 构造下单支付链接
		String params = QfWxPayController.getQfWxPayUrl(goodsOrder);
		//TODO 返回下单支付链接
		return TableResult.DateResult(params);
	}

	@Override
	public GoodsOrder selectById(Serializable id){
		GoodsOrder goodsOrder = super.selectById(id);
		GoodsOrderItem item = new GoodsOrderItem();
		item.setOrderNo(goodsOrder.getOrderNo());
		List<GoodsOrderItem> goodsOrderItems = goodsOrderItemMapper.selectOrderItemList(item);
		goodsOrder.setOrderItems(goodsOrderItems);
		return goodsOrder;
	}
}
